#include "store.h"
#include "api_server.h"
#include "controller.h"
#include "kubelet.h"
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include "spdlog/spdlog.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"

spdlog::logger *gp_logger = nullptr;

spdlog::logger* get_logger() {
    if (gp_logger) {
        return gp_logger;
    }
    try {
        // 创建控制台sink
        auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
        console_sink->set_level(spdlog::level::info);
        console_sink->set_pattern("[%Y-%m-%d %H:%M:%S] [%^%l%$] %v");        
        // // 创建文件sink
        // auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/app.log", true);
        // file_sink->set_level(spdlog::level::trace);
        // file_sink->set_pattern("[%Y-%m-%d %H:%M:%S] [%l] %v");        
        // 创建具有多个sink的logger
        // spdlog::logger logger("multi_sink", {console_sink, file_sink});
        gp_logger = new spdlog::logger("multi_sink", {console_sink});
        gp_logger->set_level(spdlog::level::trace);
        gp_logger->flush_on(spdlog::level::warn);
    } catch (const spdlog::spdlog_ex& ex) {
        std::cout << "Log initialization failed: " << ex.what() << std::endl;
        return gp_logger;
    }
    return gp_logger;
}

int main(int argc, char* argv[]) {
    spdlog::logger *logger = get_logger();
    logger->info("Nano Kubernetes startup...");
    logger->warn("** This is the development version only. **");
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " [apiserver|controller|kubelet] [options]" << std::endl;
        return 1;
    }
    std::string mode = argv[1];
    if (mode == "apiserver") {
        nanok::Store store("./data");
        // 创建并启动服务器
        nanok::APIServer server(&store, 8090);
        if (!server.start()) {
            return 1;
        }
    } else if (mode == "controller") {
        std::cout << "main.cpp main 1" << std::endl;
        nanok::ControllerManager controller("localhost:8090");
        controller.Start();
        // 保持控制器运行
        while (true) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    } else if (mode == "kubelet") {
        // nanok::Store store("./data");
        std::string nodeName = "node-1";
        if (argc > 2) nodeName = argv[2];
        
        nanok::Kubelet kubelet(nodeName, "localhost:8090");
        kubelet.Start();
        
        // 保持 kubelet 运行
        while (true) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    } else {
        std::cerr << "Unknown mode: " << mode << std::endl;
        return 1;
    }
    
    return 0;
}